package zerous.infinite.ui;

import com.badlogic.gdx.scenes.scene2d.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.math.*;
import com.badlogic.gdx.scenes.scene2d.utils.*;
import zerous.infinite.*;
import com.badlogic.gdx.*;
import zerous.infinite.util.*;
import zerous.infinite.core.*;

public class Rocker extends Actor implements Entity.EntityController {
	Sprite rocker, limit;
	Vector2 position, rockerPos;
	
	Vector2 direction;
	int size = Gdx.graphics.getWidth() / 4;
	int r = size/2;
	public Rocker(float x, float y) {
		
		
		limit = new Sprite(Assets.ROCKER_LIMIT);
		limit.setAlpha(0x80);
		limit.setSize(size, size);
		
		rocker = new Sprite(Assets.ROCKER);
		rocker.setAlpha(0x80);
		rocker.setSize(size/2, size/2);
		
		setSize(limit.getWidth(), limit.getHeight());
		setPosition(x, y);
		
		position = new Vector2(x, y);
		direction = new Vector2();
		rockerPos = new Vector2(limit.getWidth()/2, limit.getHeight()/2);
		limit.setPosition(position.x, position.y);
		//rocker.setPosition(limit.getWidth()/2, position.y+rockerPos.y-rocker.getHeight()/2);
		resetRocker();
		initControl();
	}
	
	private void initControl() {
		addListener(new DragListener() {
			@Override
			public void drag(InputEvent i, float x, float y, int pointer) {
				float distance = MathUtil.distance(x, y, limit.getWidth()/2, limit.getHeight()/2);
				float sin = ((y - size/2)/distance);
				float cos = ((x - size/2)/distance);
				direction.set(cos, sin);
				if (distance < limit.getWidth()/2) {
					rockerPos.set(x, y);
				} else {
					float rx = size/2+r * cos;
					float ry = size/2+r * sin;
					rockerPos.set(rx, ry);
				}
			}
			
			@Override
			public void dragStop(InputEvent i, float x, float y, int pointer) {
				rockerPos.set(limit.getWidth()/2, limit.getHeight()/2);
				direction.setZero();
			}
		});
	}

	@Override
	public Vector2 getDirection() {
		return direction;
	}

	@Override
	public void act(float delta) {
		super.act(delta);
		resetRocker();
	}

	@Override
	public void draw(Batch batch, float parentAlpha) {
		super.draw(batch, parentAlpha);
		
		//Assets.fnt.draw(batch, rockerPos+"",  Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2);
		
		limit.draw(batch);
		rocker.draw(batch);
	}
	
	private void resetRocker() {
		rocker.setPosition(position.x+rockerPos.x-rocker.getWidth()/2, position.y+rockerPos.y-rocker.getHeight()/2);
	}
}
